package com.ivanceras.client.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.Widget;
import com.ivanceras.client.xml.XmlDataProvider;
import com.ivanceras.shared.db.DAO;

public class XmlReaderUI extends Composite{

	private static XmlReaderUIUiBinder uiBinder = GWT
	.create(XmlReaderUIUiBinder.class);

	interface XmlReaderUIUiBinder extends UiBinder<Widget, XmlReaderUI> {
	}

	@UiField
	FileUpload gwtFileUpload;

	public XmlReaderUI() {
		initWidget(uiBinder.createAndBindUi(this));
		gwtFileUpload.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				NativeEvent evt = event.getNativeEvent();
				handleXmlDataFile(evt, new AsyncFileReadAsStringCallback() {

					@Override
					public void onSuccess(String str) {
						XmlDataProvider prd = new XmlDataProvider(str);
						DAO[] daoList = prd.getDaoList("ad_window", 1, 10);
						for(DAO dao : daoList){
							System.out.println(" "+dao.getModelName()+" ["+dao.get_Value("ad_window_id")+"]");
							System.out.println(" "+dao.getProperties());
						}
					}

					@Override
					public void onFailure(Throwable caught) {
						System.err.println("Error!");

					}
				});
			}
		});


	}

	native void handleXmlDataFile(NativeEvent evt, AsyncFileReadAsStringCallback callback)/*-{
		var files = evt.target.files;
		for (var i = 0, f; f = files[i]; i++) {
			var reader = new FileReader();
			reader.onload = (function(theFile) {
				return function(e){
					callback.@com.ivanceras.client.widgets.AsyncFileReadAsStringCallback::onSuccess(Ljava/lang/String;)(e.target.result);
				}
			})(f);
			reader.readAsText(f,"UTF-8");
		}
	}-*/;
}
